package com.dragon.aipictures.Controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dragon.aipictures.Exception.BusinessException;
import com.dragon.aipictures.Exception.StateCode;
import com.dragon.aipictures.annotation.AuthCheck;
import com.dragon.aipictures.common.BaseResponse;
import com.dragon.aipictures.common.DeleteRequest;
import com.dragon.aipictures.constant.UserConstant;
import com.dragon.aipictures.domain.Enum.SpaceLevelEnum;
import com.dragon.aipictures.domain.dto.request.space.SpaceAddRequest;
import com.dragon.aipictures.domain.dto.request.space.SpaceEditRequest;
import com.dragon.aipictures.domain.dto.request.space.SpaceQueryRequest;
import com.dragon.aipictures.domain.dto.request.space.SpaceUpdateRequest;
import com.dragon.aipictures.domain.entity.Space;
import com.dragon.aipictures.domain.entity.User;
import com.dragon.aipictures.domain.vo.space.SpaceLevel;
import com.dragon.aipictures.domain.vo.space.SpaceVO;
import com.dragon.aipictures.manager.auth.SpaceUserAuthManager;
import com.dragon.aipictures.manager.auth.annotation.SaSpaceCheckPermission;
import com.dragon.aipictures.manager.auth.model.SpaceUserPermissionConstant;
import com.dragon.aipictures.service.pictureService;
import com.dragon.aipictures.service.spaceService;
import com.dragon.aipictures.service.userService;
import com.dragon.aipictures.util.ResultUtils;
import com.dragon.aipictures.util.ThrowUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/space")
public class SpaceController {
    @Resource
    private userService userService;
    @Resource
    private pictureService pictureService;
    @Resource
    private spaceService spaceService;
    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateSpace(@RequestBody SpaceUpdateRequest spaceUpdateRequest) {
        if (spaceUpdateRequest == null || spaceUpdateRequest.getId() <= 0||spaceUpdateRequest.getId()==null) {
            throw new BusinessException(StateCode.PARAMS_ERROR);
        }
        if(ObjectUtil.isAllEmpty(spaceUpdateRequest.getSpaceName(),spaceUpdateRequest.getSpaceLevel(),spaceUpdateRequest.getMaxCount(),spaceUpdateRequest.getMaxSize())){
            throw new BusinessException(StateCode.PARAMS_ERROR,"请输入要更新的参数");
        }
        // 将实体类和 DTO 进行转换
        Space space = new Space();
        BeanUtils.copyProperties(spaceUpdateRequest, space);
        // 自动填充数据
        spaceService.fillSpaceBySpaceLevel(space);
        // 数据校验
        spaceService.validSpace(space, false);
        // 判断是否存在
        long id = spaceUpdateRequest.getId();
        Space oldSpace = spaceService.getById(id);
        ThrowUtil.throwIf(oldSpace == null, StateCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = spaceService.updateById(space);
        ThrowUtil.throwIf(!result, StateCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    @PostMapping("/add")
//    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.)
    public BaseResponse<Long> addSpace(@RequestBody SpaceAddRequest spaceAddRequest,HttpServletRequest request) {
        if (spaceAddRequest == null ) {
            throw new BusinessException(StateCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        Long spaceId = spaceService.addSpace(spaceAddRequest, loginUser);
        return ResultUtils.success(spaceId);
    }
    @PostMapping("/delete")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.SPACE_USER_MANAGE)
    public BaseResponse<Boolean> deleteSpace(@RequestBody DeleteRequest deleteRequest
            , HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(StateCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        Long id = deleteRequest.getId();
        // 判断是否存在
        Space oldSpace = spaceService.getById(id);
        ThrowUtil.throwIf(oldSpace == null, StateCode.NOT_FOUND_ERROR);
        // 仅本人或者管理员可删除
        spaceService.checkSpaceAuth(loginUser, oldSpace);
        // 操作数据库
        boolean result = spaceService.removeById(id);
        ThrowUtil.throwIf(!result, StateCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }
    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<SpaceVO>> listSpaceVOByPage(@RequestBody SpaceQueryRequest spaceQueryRequest,
                                                         HttpServletRequest request) {
        long current = spaceQueryRequest.getCurrent();
        long size = spaceQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtil.throwIf(size > 20, StateCode.PARAMS_ERROR);
        // 查询数据库
        Page<Space> spacePage = spaceService.page(new Page<>(current, size),
                spaceService.getQueryWrapper(spaceQueryRequest));
        // 获取封装类
        return ResultUtils.success(spaceService.getSpaceVOPage(spacePage, request));
    }
    @PostMapping("/edit")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.SPACE_USER_MANAGE)
    public BaseResponse<Boolean> editSpace(@RequestBody SpaceEditRequest spaceEditRequest, HttpServletRequest request) {
        if (spaceEditRequest == null || spaceEditRequest.getId() <= 0) {
            throw new BusinessException(StateCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        Space space = new Space();
        BeanUtils.copyProperties(spaceEditRequest, space);
        // 自动填充数据
        spaceService.fillSpaceBySpaceLevel(space);
        // 设置编辑时间
        space.setEditTime(new Date());
        // 数据校验
        spaceService.validSpace(space, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = spaceEditRequest.getId();
        Space oldSpace = spaceService.getById(id);
        ThrowUtil.throwIf(oldSpace == null, StateCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
//        spaceService.checkSpaceAuth(loginUser, oldSpace);
        // 操作数据库
        boolean result = spaceService.updateById(space);
        ThrowUtil.throwIf(!result, StateCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }
    @GetMapping("/list/level")
    public BaseResponse<List<SpaceLevel>> listSpaceLevel() {
        List<SpaceLevel> spaceLevelList = Arrays.stream(SpaceLevelEnum.values()) // 获取所有枚举
                .map(spaceLevelEnum -> new SpaceLevel(
                        spaceLevelEnum.getValue(),
                        spaceLevelEnum.getText(),
                        spaceLevelEnum.getMaxCount(),
                        spaceLevelEnum.getMaxSize()))
                .collect(Collectors.toList());
        return ResultUtils.success(spaceLevelList);
    }
    @GetMapping("/get/vo")
    public BaseResponse<SpaceVO> getSpaceVOById(long id, HttpServletRequest request) {
        ThrowUtil.throwIf(id <= 0, StateCode.PARAMS_ERROR);
        // 查询数据库
        Space space = spaceService.getById(id);
        ThrowUtil.throwIf(space == null, StateCode.NOT_FOUND_ERROR);
        SpaceVO spaceVO = spaceService.getSpaceVO(space, request);
        User loginUser = userService.getLoginUser(request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        spaceVO.setPermissionList(permissionList);
        // 获取封装类
        return ResultUtils.success(spaceVO);
    }


}
